#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define THRNUM	4

static pthread_mutex_t mutex[THRNUM];

//参数结构体
struct thr_arg_st
{
	int n;
};

//next小函数
int next(int n)
{
	if(n == THRNUM - 1)
		return 0;
	return n + 1;
}
//线程处理函数
static void * thr_func(void * p)
{
	int n = ((struct thr_arg_st *)p)->n;
	int c = 'a' + n;
	while(1)
	{
		pthread_mutex_lock(&mutex[n]);			//上自己的锁
		write(1, &c, 1);						//输出字符
		pthread_mutex_unlock(&mutex[next(n)]);	//解下一个人的锁
	}
	return NULL;
}
int main()
{
	pthread_t tid[THRNUM];
	int i, err;
	//循环n次
	for(i = 0; i < THRNUM; i++)
	{
		//设置参数
		struct thr_arg_st * argp;
		argp = malloc(sizeof(*argp));
		if(argp  == NULL)
		{
			perror("malloc");
			exit(1);
		}
		argp->n = i;
		//初始化第i把锁
		pthread_mutex_init(&mutex[i], NULL);
		//锁住第i把锁
		pthread_mutex_lock(&mutex[i]);	
		//创建线程		
		err = pthread_create(&tid[i], NULL, thr_func, argp);
		if(err)
		{
			fprintf(stderr, "create:%s\n", strerror(err));
			exit(1);
		}
	}
	//解开第0把锁(连锁反应)
	pthread_mutex_unlock(&mutex[0]);
	//定时3秒
	alarm(3);
	//回收线程(假的!)
	for(i = 0; i < THRNUM; i++)
	{
		pthread_join(tid[i], NULL);
	}
	//销毁所有的互斥锁
	for(i = 0; i < THRNUM; i ++)
	{
		pthread_mutex_destroy(&mutex[i]);
	}

	exit(0);
}